import { isCrypto } from '@/assets/config.js';
import $utils from '@/plugins/utils';
import store from '@/store';
const { showLoading, showToast, getCurPage,aesDecrypt } = $utils;

export default res => {
    return new Promise((resolve, reject) => {
        const httpSuccess = res.data && (Number(res.statusCode) >= 200 && Number(res.statusCode) < 400);
        if (httpSuccess) {
            let rs = {};
            // #ifdef H5
            rs = res.data ? res.data : {};
            // #endif

            // #ifndef H5
            rs = res.data ? JSON.parse(res.data) : {};
            // #endif

            const hshCode = rs.returnCode === 0 || rs.errorCode === 1 ? '200' : '400';
            const hshMsg = rs.returnMsg ? rs.returnMsg : rs.msg ? rs.msg : rs.errMsg;
            rs.code = rs.code ? rs.code : hshCode;
            rs.msg = hshMsg;
            if (rs.code.toString() === '200') {
                const contentType = res.header['content-type'] || res.header['Content-Type'];
                if ((contentType === undefined || contentType.indexOf('application/json') > -1) && Number(isCrypto)){
                    rs.data = aesDecrypt(rs.data);
                }
                resolve(rs);
            } else if (rs.msg && rs.msg.indexOf('请求访问令牌非法') > -1 || rs.msg.indexOf('token过期') > -1 || rs.code
                .toString() === '500') {
                store.commit('commitClear');
                showToast({ 'title': '请求访问令牌非法' });
                setTimeout(() => {
                    const page = getCurPage().route;
                    if (page !== 'pages/login/index') {
                        uni.reLaunch({
                            'url': '/pages/login/index'
                        });
                    }
                }, 1501);
            } else {
                reject(rs.msg);
            }
        } else {
            // uni.showModal(OBJECT);
            showToast({ 'title': '请求失败，请稍后再试' });
            reject(res.data || res.msg);
        }
    });
};